package com.iwhalecloud.bss.kite.cucc.service.shoppingcart.query;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.cart.client.api.cart.operate.IOperateKiteCartService;
import com.iwhalecloud.bss.kite.cart.client.api.cart.query.IQueryKiteCartService;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartQueryRequestDTO;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartListUtils;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartObjectUtils;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartStringUtils;
import com.iwhalecloud.bss.kite.cart.dataservice.entity.CartItemRel;
import com.iwhalecloud.bss.kite.cart.dataservice.mapper.shoppingcart.KiteCartItemRelMapper;
import com.iwhalecloud.bss.kite.client.api.shoppingcart.operate.IOperateShoppingCartItemService;
import com.iwhalecloud.bss.kite.client.api.shoppingcart.operate.IOperateShoppingCartService;
import com.iwhalecloud.bss.kite.client.api.shoppingcart.query.IQueryShoppingCartItemService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartGroupInstDTO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.query.ICuccQueryShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.AttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodsDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccQryResultConfigCache;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferDetailCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ServiceOfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteShoppingCartGroupInst;
import com.iwhalecloud.bss.kite.dataservice.entity.ServiceOffer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.dataservice.mapper.shoppingcart.ShoppingCartGroupInstMapper;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
public class CuccQueryShoppingCartService implements ICuccQueryShoppingCartService {

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateShoppingCartService shoppingCartService;

    @Autowired
    IQueryShoppingCartItemService queryShoppingCartItemService;

    @Autowired
    IOperateShoppingCartItemService operateShoppingCartItemService;

    @Autowired
    IOperateKiteCartService operateKiteCartService;

    private static final String STATUSCD_ATTRID = "2020000215";

    @Override
    public Integer getShoppingCartGroupCount(KiteCartQueryRequestDTO request) {
        IQueryKiteCartService queryKiteCartService = SpringUtil.getBean(IQueryKiteCartService.class);
        List<ShoppingCartGroupInstDTO> groupInstBaseDTOS = queryKiteCartService.listShoppingCartGroupInsts(request)
            .getResultObject();

        // 过滤掉失效的购物车数据
        List<ShoppingCartGroupInstDTO> shoppingCartGroupInstDTOS = this.dealOtherInfo(groupInstBaseDTOS, request);
        int count = 0;
        if (KiteListUtils.isNotEmpty(shoppingCartGroupInstDTOS)) {
            count = shoppingCartGroupInstDTOS.size();
        }

        return count;
    }

    @Override
    public List<ShoppingCartGroupInstDTO> createShoppingCartGroups(String staffId, String lanId, String custId) {
        return null;
    }

    @Override
    public List<ShoppingCartGroupInstDTO> listShoppingCartGroupInsts(KiteCartQueryRequestDTO request) {
        IQueryKiteCartService queryKiteCartService = SpringUtil.getBean(IQueryKiteCartService.class);
        List<ShoppingCartGroupInstDTO> groupInstDTOS = queryKiteCartService.queryKiteCarts(request).getResultObject();
        // 一些数据转换不适合在购物车工程做，先需要在极简做一层转换
        List<ShoppingCartGroupInstDTO> shoppingCartGroupInstDTOS = this.dealOtherInfo(groupInstDTOS, request);
        return shoppingCartGroupInstDTOS;
    }

    @Override
    public PageInfo<ShoppingCartGroupInstDTO> listGroupInstsPage(KiteCartQueryRequestDTO request) {
        IQueryKiteCartService queryKiteCartService = SpringUtil.getBean(IQueryKiteCartService.class);
        List<String> specIds = new ArrayList<>();
        if (KiteCartStringUtils.isNotBlank(request.getCategoryId())) {
            listSpecId(request, specIds);
        }

        if (1 == CuccQryResultConfigCache.getQueryResutConfig(request.getStaffId())) {
            // 查看草稿及待提交
            request.setStatusCd("1800,1100");
        }

        PageInfo<ShoppingCartGroupInstDTO> groupInstDTOS = queryKiteCartService.queryKiteCartsPage(request, specIds);
        // 一些数据转换不适合在购物车工程做，先需要在极简做一层转换
        List<ShoppingCartGroupInstDTO> shoppingCartGroupInstDTOS = this.dealOtherInfo(groupInstDTOS.getList(), request);
        PageInfo<ShoppingCartGroupInstDTO> pageInfo = new PageInfo<>();
        KiteBeanUtils.copyProperties(groupInstDTOS, pageInfo);
        pageInfo.setList(shoppingCartGroupInstDTOS);
        return pageInfo;
    }

    private void listSpecId(KiteCartQueryRequestDTO request, List<String> specIds) {
        IGoodsService goodsService = SpringUtil.getBean(IGoodsService.class);
        List<GoodsDTO> list = goodsService.queryGoodsListInCategroy(request.getCategoryId(), null);
        if(KiteListUtils.isNotEmpty(list) && KiteStringUtils.isNotEmpty(request.getCategoryId())) {
            String codea = DcPublicCache.getCodea("20210914001", request.getCategoryId());
            if (KiteStringUtils.isNotEmpty(codea)) {
                String[] selectableIdArr = codea.split(SymbolConsts.COMMA);
                for (int i = list.size() - 1; i >= 0; i--) {
                    if(!KiteStringUtils.equalsAny(list.get(i).getCateId(), selectableIdArr)) {
                        list.remove(i);
                    }
                }
            }
        }
        List<String> skuList = list.stream().map(GoodsDTO::getGoodsSku).collect(Collectors.toList());
        skuList.forEach(sku -> {
            DataResult<List<AttrDTO>> result = goodsService.queryGoodKeyAttrsByProvince(sku);
            List<AttrDTO> attrDTOS = result.getResultObject();
            if (KiteListUtils.isEmpty(attrDTOS)) {
                return;
            }
            List<String> skus = attrDTOS.stream().map(AttrDTO::getGoodsSku).collect(Collectors.toList());
            skus = skus.stream()
                .collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o))),
                    ArrayList::new));
            specIds.addAll(skus);
        });
    }

    private List<ShoppingCartGroupInstDTO> dealOtherInfo(List<ShoppingCartGroupInstDTO> shoppingInfoList, KiteCartQueryRequestDTO request) {
        List<ShoppingCartGroupInstDTO> groupInstDtos = new ArrayList<ShoppingCartGroupInstDTO>();
        if (KiteCartListUtils.isNotEmpty(shoppingInfoList)) {
            String userName = "";
            if (ContextUtil.getLoginInfo() != null) {
                userName = ContextUtil.getLoginInfo().getUserInfo().getUserName();
            }
            for (ShoppingCartGroupInstDTO shoppingInfo : shoppingInfoList) {
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String a = sdf.format(date);

//                if (KeyConsts.SHOPPING_CART_GROUP_STATUS_INPUT.equals(shoppingInfo.getStatusCd())) {
//                    ShoppingCartGroupInstDTO cacheGroupInstDto = ShoppingCartGroupCache
//                        .getGroupInstDto(shoppingInfo.getCreateStaff(), shoppingInfo.getCustId(), shoppingInfo.getGroupId());
//                    if (KiteObjectUtils.isEmpty(cacheGroupInstDto)) {
//                        /*TransactionUtils.executeNew(() -> {
//                            IOperateKiteCartService queryKiteCartService = SpringUtil.getBean(IOperateKiteCartService.class);
//                            KiteCartDeleteRequestDTO delRequest = new KiteCartDeleteRequestDTO();
//                            delRequest.setCartId(request.getCartId());
//                            delRequest.setGroupIds(Collections.singletonList(shoppingInfo.getGroupId()));
//                            queryKiteCartService.deleteKiteCart(delRequest);
//
//                        });*/
//                        continue;
//                    }
//                }
//                KiteCartRequestDTO request1 = new KiteCartRequestDTO();
//                request1.setStaffId(shoppingInfo.getCreateStaff());
//                request1.setCartId(shoppingInfo.getCartId());
//                request1.setCustId(shoppingInfo.getCustId());
//                request1.setGroupId(shoppingInfo.getGroupId());

                //SpringUtil.getBean(ICuccOperateShoppingCartService.class).createShoppingCartGroupInstInfo(request1);
                String specId = shoppingInfo.getSpecId();
                Offer offer = OfferCache.get(specId);
                if (Objects.nonNull(offer)) {
                    shoppingInfo.setCateId(offer.getCateId());
                    shoppingInfo.setOfferId(specId);
                    shoppingInfo.setSpecName(offer.getOfferName());
                    shoppingInfo.setOfferType(offer.getOfferType());
                }

                if (KiteStringUtils.isNotEmpty(request.getCategoryId()) && !KiteStringUtils
                    .isEqual(request.getCategoryId(), shoppingInfo.getCateId())) {
                    continue;
                }

                ServiceOffer serviceOffer = ServiceOfferCache.get(shoppingInfo.getServiceOfferId());

                if (Objects.nonNull(serviceOffer)) {
                    //业务动作
                    shoppingInfo.setServiceOfferName(serviceOffer.getServiceOfferName());
                }
                else {
                    shoppingInfo.setServiceOfferId("1");
                    shoppingInfo.setServiceOfferName("订购");
                }
                // 订单状态
                if (KiteCartStringUtils.isNotEmpty(shoppingInfo.getStatusCd())) {

                    AttrValue statusAttrValue = AttrValueCache
                        .getAttrValue(STATUSCD_ATTRID, shoppingInfo.getStatusCd());
                    if (!KiteCartObjectUtils.isEmpty(statusAttrValue)) {
                        shoppingInfo.setStatusName(statusAttrValue.getAttrValueName());
                        shoppingInfo.setStatusCd(shoppingInfo.getStatusCd());
                    }
                }
                if (KiteStringUtils.isEmpty(shoppingInfo.getCreateStaffName())) {
                    shoppingInfo.setCreateStaffName(userName);

                }
                if (KiteStringUtils.isEmpty(shoppingInfo.getCustManagerName())) {
                    shoppingInfo.setCustManagerName(userName);

                }
                groupInstDtos.add(shoppingInfo);
            }
        }
        return groupInstDtos;
    }

    @Override
    public List<ShoppingCartGroupInstDTO> createSimpleShoppingCartGroupList(String staffId, String lanId,
                                                                            String custId) {
        return null;
    }

    @Override
    public List<ShoppingCartGroupInstDTO> listChargingShoppingCartGoups(String staffId, String lanId, String custId) {
        return null;
    }

    @Override
    public String getShoppingCartId(String staffId, String custId) {
        return operateKiteCartService.getShoppingCartId(staffId, custId).getResultObject();
    }

    @Override
    public List<ShoppingCartGroupInstDTO> queryKiteCartDetails(String sceneInstId, String cartId, String offerId, String custId, String statusCd, String serviceOfferId) {
        ShoppingCartGroupInstMapper shop = SpringUtil.getBean(ShoppingCartGroupInstMapper.class);
        KiteShoppingCartGroupInst shoppingCartGroupInst = shop.listShoppingCartGroupInstByCartId(sceneInstId, custId, cartId);
        if (KiteObjectUtils.isEmpty(shoppingCartGroupInst)) {
            return new ArrayList<>();
        }

        KiteCartItemRelMapper cartItemRelMapper = SpringUtil.getBean(KiteCartItemRelMapper.class);
        List<CartItemRel> rels = cartItemRelMapper.listCartItemRelsByACartItemId(shoppingCartGroupInst.getCartItemId(), shoppingCartGroupInst.getCartId(), shoppingCartGroupInst.getCustId());
        if (KiteListUtils.isEmpty(rels)) {
            return new ArrayList<>();
        }
        Offer mainOffer = OfferCache.get(offerId);
        String offerType = mainOffer.getOfferType();
        if (KiteStringUtils.equals(KeyConsts.OFFER_TYPE_15, offerType)) {
            List<ShoppingCartGroupInstDTO> groupInstDtos = new ArrayList<>();
            List<OfferDetail> offerDetails = OfferDetailCache.get(offerId);
            if (KiteListUtils.isNotEmpty(offerDetails)) {
                for (CartItemRel cartItemRel : rels) {
                    String itemSpecId = cartItemRel.getzApplyObjSpec();
                    String userName = "";
                    if (ContextUtil.getLoginInfo() != null) {
                        userName = ContextUtil.getLoginInfo().getUserInfo().getUserName();
                    }
                    for (OfferDetail offerDetail : offerDetails) {
                        String specId = offerDetail.getObjId();
                        if (!KiteStringUtils.isEqual(itemSpecId, specId)) {
                            continue;
                        }
                        Offer offer = OfferCache.get(specId);

                        if (Objects.isNull(offer)) {
                            continue;
                        }
                        ShoppingCartGroupInstDTO shoppingInfo = new ShoppingCartGroupInstDTO();
                        shoppingInfo.setGroupId(sceneInstId);
                        shoppingInfo.setCartId(cartId);
                        shoppingInfo.setServiceOfferId(serviceOfferId);
                        shoppingInfo.setCustId(custId);
                        shoppingInfo.setOfferInstId(cartItemRel.getzObjId());
                        shoppingInfo.setOfferId(specId);
                        shoppingInfo.setCateId(offer.getCateId());
                        shoppingInfo.setSpecName(offer.getOfferName());
                        shoppingInfo.setOfferType(offer.getOfferType());
                        shoppingInfo.setAmount("1");
                        shoppingInfo.setIsDelete("F");

                        ServiceOffer serviceOffer = ServiceOfferCache.get(serviceOfferId);
                        if (Objects.nonNull(serviceOffer)) {
                            //业务动作
                            shoppingInfo.setServiceOfferName(serviceOffer.getServiceOfferName());
                        }
                        else {
                            shoppingInfo.setServiceOfferId("1");
                            shoppingInfo.setServiceOfferName("订购");
                        }
                        // 订单状态
                        if (KiteCartStringUtils.isNotEmpty(statusCd)) {

                            AttrValue statusAttrValue = AttrValueCache
                                .getAttrValue(STATUSCD_ATTRID, statusCd);
                            if (!KiteCartObjectUtils.isEmpty(statusAttrValue)) {
                                shoppingInfo.setStatusName(statusAttrValue.getAttrValueName());
                                shoppingInfo.setStatusCd(statusCd);
                            }
                        }
                        if (KiteStringUtils.isEmpty(shoppingInfo.getCreateStaffName())) {
                            shoppingInfo.setCreateStaffName(userName);

                        }
                        if (KiteStringUtils.isEmpty(shoppingInfo.getCustManagerName())) {
                            shoppingInfo.setCustManagerName(userName);

                        }
                        shoppingInfo.setCreateDate(shoppingCartGroupInst.getCreateDate());
                        groupInstDtos.add(shoppingInfo);
                    }
                }
            }
            return groupInstDtos;
        }
        return new ArrayList<>();
    }
}
